package com.fancy.learncenter.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CourseDataBean;
import com.fancy.learncenter.bean.LessonDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.CourseDetailActivity;
import com.fancy.learncenter.ui.activity.MainActivity;
import com.fancy.learncenter.ui.activity.SplashActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.ui.view.ZoomOutPageTransformer;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Observable;
import rx.functions.Action1;

/**
 * A simple {@link Fragment} subclass.
 */
public class CourseDetailFragment extends Fragment {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    ArrayList<View> vpView;
    ViewPager viewPager;
    View topView;
    TextView content;
    TextView name;
    TextView introduce;

    List<CourseDataBean.LessonCategoryVOListBean.ChildCategoryVOListBean> childCategoryVOList;
    LayoutInflater inflater;

    List<CourseDataBean.LessonCategoryVOListBean.ChildCategoryVOListBean.MLessonVOListBean> resPagerDatas;

    MyAdapter adapter;

    public CourseDetailFragment() {

    }


    public void setData(CourseDataBean.LessonCategoryVOListBean lessonCategoryVOListBean) {
        if (lessonCategoryVOListBean.getChildCategoryVOList() != null) {
            this.childCategoryVOList = lessonCategoryVOListBean.getChildCategoryVOList();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        topView = inflater.inflate(R.layout.fragment_course_detail, container, false);
        ButterKnife.bind(this, topView);
        this.inflater = inflater;

        initView();
        initViewPager();
        return topView;
    }

    private void initView() {
        viewPager = (ViewPager) topView.findViewById(R.id.view_pager);
        content = (TextView) topView.findViewById(R.id.content);
        name = (TextView) topView.findViewById(R.id.name);
        introduce = (TextView) topView.findViewById(R.id.introduce);
    }

    private void initViewPager() {

        vpView = new ArrayList<>();
        resPagerDatas = new ArrayList<>();
        if (childCategoryVOList == null) {
            return;
        }
        for (int i = 0; i < childCategoryVOList.size(); i++) {
            for (int j = 0; j < childCategoryVOList.get(i).getMLessonVOList().size(); j++) {

                if (childCategoryVOList.get(i) != null) {

                    if (childCategoryVOList.get(i).getMLessonVOList().get(j) != null) {
                        resPagerDatas.add(childCategoryVOList.get(i).getMLessonVOList().get(j));
                        vpView.add(inflater.inflate(R.layout.fragment_course_detail_vp_item, null));
                    }
                }

            }
        }
        if (resPagerDatas.size() <= 0) {
            return;
        }
        content.setText(resPagerDatas.get(0).getTextbookDesc());
        name.setText(resPagerDatas.get(0).getLessonName());
        introduce.setText(resPagerDatas.get(0).getLessonIntro());

        ViewPagerAdapter bannerAdapter = new ViewPagerAdapter();
        viewPager.setAdapter(bannerAdapter);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer(0.6f));
        viewPager.setOffscreenPageLimit(3);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                if (resPagerDatas.size() != 0) {
                    content.setText(resPagerDatas.get(position).getTextbookDesc());
                    name.setText(resPagerDatas.get(position).getLessonName());
                    introduce.setText(resPagerDatas.get(position).getLessonIntro());

                    Observable observable = Observable.timer(100, TimeUnit.MILLISECONDS);
                    observable.subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            getAllLesson(resPagerDatas.get(position).getLessonId());
                        }
                    });

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        getAllLesson(resPagerDatas.get(0).getLessonId());

        initRecycleView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    class ViewPagerAdapter extends PagerAdapter {

        ViewPagerAdapter() {

        }

        @Override
        public int getCount() {
            return vpView.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = vpView.get(position);
            SimpleDraweeView simpleDraweeView = (SimpleDraweeView) view.findViewById(R.id.simpleDraweeView);
            simpleDraweeView.setImageURI((String) resPagerDatas.get(position).getImgUrl());
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = (View) object;
            container.removeView(view);
        }

    }


    private void initRecycleView() {
        ArrayList<LessonDataBean.LessonSchoolDetailListBean> datas = new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setNestedScrollingEnabled(false);

        adapter = new MyAdapter(getActivity(), datas);
        recyclerView.setAdapter(adapter);
    }

    class MyAdapter extends CommonRecycleViewAdapter<LessonDataBean.LessonSchoolDetailListBean> {
        Context mContext;

        public MyAdapter(Context mContext, List<LessonDataBean.LessonSchoolDetailListBean> itemDatas) {
            super(mContext, R.layout.activity_course_detail_item, itemDatas);

            this.mContext = mContext;
        }

        @Override
        public void bindView(CustomViewHold customViewHold, final LessonDataBean.LessonSchoolDetailListBean item, int position) {
            LinearLayout rootView = customViewHold.getView(R.id.rootView);
            Button courseFeeBtn = customViewHold.getView(R.id.course_fee_btn);
            // 不可以报名
            if (item.getCanSignUp() == 0) {
//                rootView.setBackgroundColor(mContext.getResources().getColor(R.color.course_no_sign));
                rootView.setBackgroundResource(R.mipmap.course_icon_no_shadow);
                courseFeeBtn.setBackgroundColor(mContext.getResources().getColor(R.color.course_fee_btn_noclick));
                rootView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.show("请先选择学校");
                    }
                });

            } else {
                rootView.setBackgroundResource(R.mipmap.course_icon_shadow);
                rootView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, MallCommonH5Activity.class);
                        intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getCourseDetail(item.getId() + "", item.getSchoolId() + ""));
                        startActivity(intent);
                    }
                });
            }

            TextView name = customViewHold.getView(R.id.name);
            name.setText(item.getName());

            TextView time = customViewHold.getView(R.id.time);
            time.setText(item.getLessonTime());
            TextView num = customViewHold.getView(R.id.num);
            num.setText(item.getLessonHoursNum() + "课时");
            TextView money = customViewHold.getView(R.id.money);

            money.setText("¥"+(int)item.getSalePrice());
        }

    }

    int lessonId;

    private void getAllLesson(int lessonId) {
        this.lessonId = lessonId;
        Map map = new HashMap();
        map.put("lessonId", lessonId);

        if (!TextUtils.isEmpty(CourseDetailActivity.schoolID)) {
            map.put("schoolId", CourseDetailActivity.schoolID);
        }

        HttpMehtod.getInstance().getALLLesson(map, new CustomNetSubscriber(getActivity(), false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<LessonDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), LessonDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<LessonDataBean>() {
                    @Override
                    public void success(LessonDataBean dataBean) {
                        adapter.notifyDataSetChanged(dataBean.getLessonSchoolDetailList());
                    }

                    @Override
                    public void fail(String errorCode) {
                    }
                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();

        getAllLesson(lessonId);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}